package com.hansheng.ssdxs.utils;

import android.util.Log;

import com.hansheng.ssdxs.base.helper.SocketHelper;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;

/**
 * ---------------------------------------------------------------
 * 作者：HanSheng
 * 邮箱：164897033@qq.com
 * 创建时间：2020/12/17  23:16
 * 文件描述：
 * ---------------------------------------------------------------
 */
public class JWebSocketClient extends WebSocketClient {

    /**
     * Constructs a WebSocketClient instance and sets it to the connect to the
     * specified URI. The channel does not attampt to connect automatically. The connection
     * will be established once you call <var>connect</var>.
     *
     * @param serverUri the server URI to connect to
     */
    public JWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    /**
     * Called after an opening handshake has been performed and the given websocket is ready to be written on.
     *
     * @param handshake The handshake of the websocket instance
     */
    @Override
    public void onOpen(ServerHandshake handshake) {
        Log.e("JWebSocketClient", "onOpen() " + handshake.getContent());
    }

    /**
     * Callback for string messages received from the remote host
     *
     * @param message The UTF-8 decoded message that was received.
     * @see #onMessage(ByteBuffer)
     **/
    @Override
    public void onMessage(String message) {
        Log.e("JWebSocketClient", "onMessage()");
    }

    /**
     * Called after the websocket connection has been closed.
     *
     * @param code   The codes can be looked up here: {@link CloseFrame}
     * @param reason Additional information string
     * @param remote
     **/
    @Override
    public void onClose(int code, String reason, boolean remote) {
        Log.e("JWebSocketClient", "onClose()");
        this.close();
        SocketHelper.getInstance().init(null);
    }

    /**
     * Called when errors occurs. If an error causes the websocket connection to fail {@link #onClose(int, String, boolean)} will be called additionally.<br>
     * This method will be called primarily because of IO or protocol errors.<br>
     * If the given exception is an RuntimeException that probably means that you encountered a bug.<br>
     *
     * @param ex The exception causing this error
     **/
    @Override
    public void onError(Exception ex) {
        Log.e("JWebSocketClient", "onError " + ex.getMessage());
    }
}
